package com.yonyou.isv.demo.openapi.api.freelogin;

import com.yonyou.isv.demo.openapi.base.datacenter.DataCenterUrlProvider;
import com.yonyou.isv.demo.openapi.base.module.reponse.ApiDataResponse;
import com.yonyou.isv.demo.openapi.api.BaseOpenApi;
import com.yonyou.isv.demo.openapi.api.OpenApiURL;
import com.yonyou.isv.demo.openapi.base.properties.OpenApiProperties;
import com.yonyou.isv.demo.openapi.base.module.common.RequestTool;
import com.yonyou.isv.demo.openapi.base.network.OpenApiRequestEncryptor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 免登示例
 * 1.在用友平台点开自己的应用页面的时候才需要免登，调用业务接口不需要免登
 * 2.在打开应用首页的时候，用友平台会将url上拼接一个code，使用request.get("code")获取到值后，做为传参调用免登接口
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FreeLoginApi extends BaseOpenApi {

    private final OpenApiProperties properties;
    private final OpenApiRequestEncryptor encryptor;
    @Resource
    DataCenterUrlProvider dataCenterUrlProvider;

    public Map<String, Object> isvFreeLogin(String code){
        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("suiteKey", properties.getAppKey());
        params.put("code", code);
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));

        // 计算签名
        String signature = encryptor.signature(params, properties.getAppSecret());
        params.put("signature", signature);
        String reqUrl = properties.concatURL(dataCenterUrlProvider.buildBusinessUrl(),OpenApiURL.INFO_BY_CODE);
        ApiDataResponse apiDataResponse = null;
        try {
            apiDataResponse = RequestTool.doGet(reqUrl,params, ApiDataResponse.class);
        } catch (IOException e) {
            log.info(e.getMessage());
        }
        return getData(apiDataResponse);
    }

}
